package com.sskj.finance.ui.fragment;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.finance.R;
import com.sskj.finance.R2;
import com.sskj.finance.bean.HomeBorrowGetTransrecordBean;
import com.sskj.finance.bean.HomeLendGetTransrecord;
import com.sskj.finance.bean.RateBean;
import com.sskj.finance.bean.SupplyData;
import com.sskj.finance.presenter.DYJKFragmentPresenter;
import com.sskj.finance.util.TipFinanUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.FINAN_FRAGMENT_DYJK)//抵押借款
public class DYJKFragment extends BaseFragment<DYJKFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @Autowired
    String type;//1押币借钱 2押钱借币
    @Autowired
    String status;
    @Autowired
    String pid;
    private MVCCoolHelper<List<HomeBorrowGetTransrecordBean>> mvcHelper;
    private SlimAdapter slimAdapter;
    private int curPos;
    private BottomSheetDialog bottomSheetDialogSupply;
    private Disposable subscribe;
    private BottomSheetDialog bottomSheetDialogPwd;

    @Override
    protected int getLayoutId() {
        return R.layout.finan_fragment_dyjk;
    }

    @Override
    public DYJKFragmentPresenter getPresenter() {
        return new DYJKFragmentPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        Map<String, String> typeMap = new HashMap<>();
        typeMap.put("1", App.INSTANCE.getString(R.string.finan_borrowActivity2_j));
        typeMap.put("2", App.INSTANCE.getString(R.string.finan_borrowActivity1_j));
        Map<String, String> riskMap = new HashMap<>();
        riskMap.put("0", App.INSTANCE.getString(R.string.finan_dYJKFragment3_j));
        riskMap.put("1", App.INSTANCE.getString(R.string.finan_dYJKFragment4_j));
        Map<String, String> statusMap = new HashMap<>();
        statusMap.put("1", App.INSTANCE.getString(R.string.finan_mortgageRecordActivity5_j));
        statusMap.put("2", App.INSTANCE.getString(R.string.finan_mortgageRecordActivity6_j));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 20))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.finan_recy_item_dyjk, new SlimInjector<HomeBorrowGetTransrecordBean>() {
            @Override
            public void onInject(HomeBorrowGetTransrecordBean data, IViewInjector injector, List payloads) {
                injector
                        .textColor(R.id.tvFirstLeft, ContextCompat.getColor(App.INSTANCE, data.getType().equals("1") ? R.color.finan_5ae : R.color.finan_878))
                        .text(R.id.tvTime, data.getAddtime())
                        .text(R.id.tvFirstLeft, typeMap.get(data.getType()))
                        .text(R.id.tvFirstRight, String.format("%s/%s", data.getRisk() + "%", statusMap.get(data.getStatus())))
                        .text(R.id.tvSecondLeft, String.format("%s %s", data.getOut_num(), data.getOut_pname()))
                        .text(R.id.tvSecondRight, String.format("%s %s", data.getIn_num(), data.getIn_pname()))
                        .text(R.id.tvThirdLeft, data.getRate() + "%")
                        .text(R.id.tvThirdRight, String.format("%s %s", data.getFee(), data.getOut_pname()))
                        .text(R.id.tvFourLeft, data.getEndtime())
                        .visibility(R.id.tvRedeem, data.getStatus().equals("1") ? View.VISIBLE : View.GONE)

                        .text(R.id.tvFourRight, data.getDays())
                        .clicked(R.id.tvRedeem, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
//                            mPresenter.getRate(data.getTran_id());
                            showCancel(null);
                        })
                        .clicked(R.id.tvSupply, v -> {
                            curPos = slimAdapter.getData().indexOf(data);
                            mPresenter.getSupplyData(data.getOut_pname());
                        })
                ;
                if (data.getStatus().equals("2")) {
                    injector.visibility(R.id.llFive, View.VISIBLE)
                            .text(R.id.tvFiveLeft, data.getSelltime());
                } else {
                    injector.visibility(R.id.llFive, View.GONE);
                }
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<HomeBorrowGetTransrecordBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<HomeBorrowGetTransrecordBean>)
                page -> mPresenter.homeBorrowGetTransrecord(type, status, pid, page + "", "20"), 20);
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();

        LiveDataBus.get().with(RxBusCode.UPDATE_DYKF_TYPE, String.class)
                .observe(this, s -> {
                    type = s;
                    mvcHelper.refresh();
                });
        LiveDataBus.get().with(RxBusCode.UPDATE_DYKF_STATUS, String.class)
                .observe(this, s -> {
                    status = s;
                    mvcHelper.refresh();
                });
        LiveDataBus.get().with(RxBusCode.UPDATE_BORROW, Integer.class)
                .observe(this, o -> {
                    mvcHelper.refresh();
                });

    }

    public void showSupply(SupplyData supplyData) {
        HomeBorrowGetTransrecordBean dataItem = (HomeBorrowGetTransrecordBean) slimAdapter.getDataItem(curPos);
        bottomSheetDialogSupply = TipFinanUtil.showSupply(getActivity(), supplyData.getUsable(), supplyData.getMark(), str -> {
            bottomSheetDialogSupply.dismiss();
            mPresenter.supply(dataItem.getTran_id(), dataItem.getOut_pname(), str[0], str[1]);
        });
        bottomSheetDialogSupply.show();


    }

    public void showCancel(RateBean rateBean) {
//        if (rateBean.getIs_adv() == 2) {
//            TipUtil.getSureCancelTip(getActivity(), App.INSTANCE.getString(R.string.finan_dYJKFragment7_j), () -> {
//                HomeBorrowGetTransrecordBean dataItem = (HomeBorrowGetTransrecordBean) slimAdapter.getDataItem(curPos);
//                mPresenter.homeBorrowPayback(dataItem.getTran_id());
//            }).show();
//        } else {
            TipUtil.getSureCancelTip(getActivity(), App.INSTANCE.getString(R.string.finan_dYJKFragment8_j), () -> {
                HomeBorrowGetTransrecordBean dataItem = (HomeBorrowGetTransrecordBean) slimAdapter.getDataItem(curPos);
                bottomSheetDialogPwd = BottomSheetUtil.showPwd(getActivity(), str -> {
                    bottomSheetDialogPwd.dismiss();

                    mPresenter.homeBorrowPayback(dataItem.getTran_id(),str[0]);
                });
                bottomSheetDialogPwd.show();
            }).show();
//        }
    }

    /**
     * 理财赎回成功
     */
    public void backSuccess() {
        mvcHelper.refresh();
    }

    public void supplySuccess() {
        mvcHelper.refresh();
    }
}
